package top.lshaci.learning.springboot.security.web.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * HelloController
 *
 * @author lshaci
 * @since 1.0.0
 */
@RestController
@RequestMapping("/hello")
public class HelloController {

    @GetMapping("/index")
//    @PreAuthorize("isAnonymous()")
    public String index() {
        return "Hello, Spring Security Index!";
    }

    /**
     * 获取当前登录用户名
     *
     * @return
     */
    @GetMapping("/username")
    public String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            username = ((org.springframework.security.core.userdetails.UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        return username;
    }
}
